package util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Locale;

public class FileUtil {

    public static File createRecordFile(String resourceName) {

        String parentDirName = "";
        // String parentDirName = "C:\\tmp\\resource";

        String os = System.getProperty("os.name");
        if (0 <= os.indexOf("Windows")) {
            parentDirName = "C:\\tmp\\resource";
        } else if (0 <= os.indexOf("Linux")) {
            parentDirName = System.getProperty("user.home")
                    + System.getProperty("file.separator") + "timer";
        } else if (0 <= os.indexOf("Mac")) {
            parentDirName = System.getProperty("user.home")
                    + System.getProperty("file.separator") + "timer";
        } else {
            parentDirName = System.getProperty("user.home")
                    + System.getProperty("file.separator") + "timer";
        }

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
                "yyyyMMdd-HHmmss", Locale.JAPAN);
        String dirName = simpleDateFormat.format(new java.util.Date());

        File recordFile = null;
        try {
            File directory = new File(parentDirName, dirName);
            recordFile = new File(directory, resourceName + ".csv");
            directory.mkdir();
            recordFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return recordFile;
    }

    /***
     * 処理の実行に要した時間を書き込みます。
     * 
     * @param file
     * @param time
     */
    public static void writeExecuteTime(File file, long time) {

        BufferedWriter bufferedWriter = null;
        try {
            bufferedWriter = FileUtil.fileWriter(file);
            bufferedWriter.write(String.valueOf(time));
            bufferedWriter.newLine();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            FileUtil.closeWriter(bufferedWriter);
        }
    }

    public static BufferedWriter fileWriter(File file) {

        BufferedWriter bufferedWriter = null;
        try {
            bufferedWriter = new BufferedWriter(new FileWriter(file, true));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bufferedWriter;
    }

    public static void closeWriter(BufferedWriter bufferedWriter) {
        if (bufferedWriter != null) {
            try {
                bufferedWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
